package com.wjw.controller;

import jakarta.annotation.PostConstruct;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ai/service")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @GetMapping(produces = "text/html;charset=UTF-8")
    public Flux<String> chat(@RequestParam("prompt") String prompt,@RequestParam("chatId") String chatId){
        return chatClient.prompt(prompt)
                .stream()
                .content();
    }
    @Autowired
    private VectorStore vectorStore;
    private OpenAiEmbeddingModel embeddingModel;

    // 自动将知识库装进向量数据库
    @PostConstruct
    public void addRAG(){
        String rag = """
                            [
                              {
                                "id": "rule_01",
                                "type": "合约期",
                                "condition": "合约期未满12个月",
                                "description": "提前更换套餐需支付剩余费用的10%作为违约金。"
                              },
                              {
                                "id": "rule_02",
                                "type": "携号转网",
                                "condition": "申请携号转网",
                                "description": "需满足：1. 无欠费 2. 当前套餐已到期 3. 非吉祥号段（如138/139开头）。"
                              }
                            ]
                """;
        //向量化
        // 1. 定义元数据（可选，用于补充文档上下文信息）
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("source", "合约规则库"); // 文档来源
        metadata.put("format", "json"); // 内容格式
        metadata.put("total_rules", 2); // 规则数量（自定义元数据）

        // 2. 构建Document对象
        Document document = Document.builder()
                .text(rag) // 核心内容：JSON字符串
                .metadata(metadata) // 附加元数据
                .id("contract_rules_001") // 可选：自定义文档ID（不设置则自动生成）
                .build();
        List<Document> documents = new ArrayList<>();
        documents.add(document);
        vectorStore.add(documents);
    }
}
